package com.emedinaa.kotlinmvvm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * CoroutineLiveData、Transformations（switchMap） 用法示例
 * 场景：根据用户输入内容 inputLiveData 异步查询结果给监听的UI observer
 * CoroutineLiveData：用于在 liveData 方法内部异步操作和发射数据，而普通liveData是其他同步或异步能力调用liveData直接设置数据，CoroutineLiveData通过livedata方法自身提供了异步能力
 */
class MyCoroutineViewModel : ViewModel() {
    val inputLiveData: MutableLiveData<String> = MutableLiveData()
    val mCoroutineLiveData = inputLiveData.switchMap {
        liveData {
            //主线程
            println("mCoroutineLiveData loading current thread:${Thread.currentThread()}")
            // dispatch loading first
            emit("LOADING")
            var result:String = ""
            //切到io线程
            withContext(Dispatchers.IO) {
                // check local storage
                kotlinx.coroutines.delay(3000)
                result = "$it 通过输入内容经过网络查询得到的数据"
            }
            println("mCoroutineLiveData result current thread:${Thread.currentThread()}")
            emit(result)
        }
    }

    val mCoroutineLiveData2 = liveData {
        //主线程
        println("mCoroutineLiveData loading current thread:${Thread.currentThread()}")
        // dispatch loading first
        emit("LOADING")
        //切到io线程
        withContext(Dispatchers.IO){
            // check local storage
            kotlinx.coroutines.delay(3000)
        }
        println("mCoroutineLiveData result current thread:${Thread.currentThread()}")
        emit("got result")
    }


}